package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.file.dto.response.FileInfoResponse;
import com.smedi.ismedi.progress.api.dto.response.FileResponse;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.File;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.MilestoneProgressDetail;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.Progress;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.ProgressDetail;
import com.smedi.ismedi.progress.core.domain.dto.FileQuery;
import com.smedi.ismedi.progress.core.domain.repository.FileRepository;
import com.smedi.ismedi.progress.core.domain.repository.MliestoneRepository;
import com.smedi.ismedi.progress.core.domain.repository.ProgressProjectRepository;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.ProgressDetailEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.ProgressEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.ProjectAttachmentImageEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProgressDetailMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProgressMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProjectAttachmentImageMapper;
import com.smedi.ismedi.progress.core.port.adapter.service.FileRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProjectRemoteService;
import com.smedi.ismedi.web.starter.common.PaginationData;
import com.smedi.ismedi.web.starter.common.ResponseData;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MILESTONE_TYPE;

/**
 * 里程碑仓库实现类
 *
 * @author liaojiajie
 * @date 2022/09/19
 */
@Repository
@AllArgsConstructor
public class MilestoneRepositoryImpl implements MliestoneRepository {
    private final AdapterConverter adapterConverter;
    private final FileRepository fileRepository;
    private final AuthorityUtil authorityUtil;
    private final ProgressDetailMapper progressDetailMapper;
    private final ProgressMapper progressMapper;
    private final ProgressProjectRepository progressProjectRepository;
    private final ProjectRemoteService projectRemoteService;
    private final ProjectAttachmentImageMapper projectAttachmentImageMapper;

    @Override
    public List<MilestoneProgressDetail> getMilestoneList(Long projectId) {
        LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId), ProgressDetailEntity::getProjectId, projectId);
        lambdaQueryWrapper.like(ProgressDetailEntity::getType, MILESTONE_TYPE);
        lambdaQueryWrapper.orderByAsc(ProgressDetailEntity::getScheduleEndTime);

        List<ProgressDetailEntity> progressDetailEntityList = progressDetailMapper.selectList(lambdaQueryWrapper);

        List<Long> ids = progressDetailEntityList.stream().map(ProgressDetailEntity::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ProjectAttachmentImageEntity> lambdaQueryWrapperImage = new LambdaQueryWrapper<>();
        lambdaQueryWrapperImage.in(ObjectUtils.isNotNull(ids), ProjectAttachmentImageEntity::getProjectScheduleDetailId, ids);
        List<ProjectAttachmentImageEntity> projectAttachmentImageEntities = projectAttachmentImageMapper.selectList(lambdaQueryWrapperImage);
        if (projectAttachmentImageEntities.size() > 0) {
            List<String> signKeys = projectAttachmentImageEntities.stream().map(ProjectAttachmentImageEntity::getSignKey).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(signKeys)){
                List<File> fileList = fileRepository.getFileList(FileQuery.builder().signKeys(signKeys).build());
                List<FileResponse> fileResponseList = new ArrayList<>();
                fileList.forEach(v->{
                    fileResponseList.add( FileResponse.builder()
                            .name(v.getName())
                            .extName(v.getExtName())
                            .signKey(v.getSignKey())
                            .url(v.getUrlOut())
                            .build());
                });
                for (ProgressDetailEntity progressDetailEntity: progressDetailEntityList){
                    List<FileResponse> photoFileList = new ArrayList<>();
                    for (ProjectAttachmentImageEntity projectAttachmentImage: projectAttachmentImageEntities) {
                        if (progressDetailEntity.getId().equals(projectAttachmentImage.getProjectScheduleDetailId())){
                            for (FileResponse file : fileResponseList){
                                if (projectAttachmentImage.getSignKey().equals(file.getSignKey())){
                                    photoFileList.add(file);
                                    break;
                                }
                            }
                        }
                    }
                    progressDetailEntity.setPhotoFile(photoFileList);

                }
            }
        }
        progressDetailEntityList.forEach(progressDetailEntity ->{
            //如果任务已完成，那么不管是否滞后都要改成正常
            if(progressDetailEntity.getCompletion() == 1){
                progressDetailEntity.setStatus(1);
            }
        });
        List<MilestoneProgressDetail> progressDetailList = adapterConverter.progressDetailEntityListToProgressDetailList(progressDetailEntityList);

        return progressDetailList;
    }

    @Override
    public Page<Progress> getMilestonePage(Long offset, Long pageSize, Long hrOrganizationId, Integer projectId, String projectManager, Integer mainCourtyardId, Integer status, String projectCategory,String projectName) {
        Page<ProgressEntity> progressEntity = new Page<>(offset, pageSize);
        ResponseData<List<ProjectBasicResponse>> projectList = new ResponseData<>();
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        List<ProjectBasicResponse> projectListData = new ArrayList<>();
        List<ProjectBasicResponse> allProjectBasicList = projectRemoteService.getAllProjectBasicList();
        //主体院条件选择   选了则传主体院id查项目
        if (mainCourtyardId == null && hrOrganizationId!=null) {
            projectList = progressProjectRepository.getProjectList(hrOrganizationId);
        }
        if (mainCourtyardId != null) {
            projectList = progressProjectRepository.getProjectList(mainCourtyardId.longValue());
        }

        List<ProjectBasicResponse> data = projectList.getData();
        //项目列表不为空 筛选ids
        if(data != null){
            projectListData = data.stream().filter(v -> {
                if (StringUtils.isNotBlank(projectCategory)) {
                    return projectCategory.equals(v.getProjectCategory());
                }
                return true;
            }).filter(v -> {
                //web 端的项目经理筛选
                if (StringUtils.isNotBlank(projectManager)) {
                    return v.getProjectManager().indexOf(projectManager) > -1;
                }
                return true;
            }).filter(v -> {
                //app根据 名称 或者 经理 筛选
                if (StringUtils.isNotBlank(projectName)) {
                    if (v.getProjectName().indexOf(projectName) > -1){
                        return true;
                    }
                    return v.getProjectManager().indexOf(projectName) > -1;
                }
                return true;
            }).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(projectListData)){
                ids =projectListData.stream().map(ProjectBasicResponse::getProjectId).collect(Collectors.toList());
            }
        }
        //如果企业组织id下没有项目   则没有项目计划
        if (hrOrganizationId !=null && CollectionUtils.isEmpty(projectListData)){
            return new Page<>();
        }
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(ids), ProgressEntity::getProjectId, ids);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(projectId), ProgressEntity::getProjectId, projectId);
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(status), ProgressEntity::getMilestoneProgressStatus, status);

        lambdaQueryWrapper.orderByAsc(ProgressEntity::getMilestoneProgressStatus);
        Page<ProgressEntity> progressEntityPage = progressMapper.selectPage(progressEntity, lambdaQueryWrapper);
        List<ProjectBasicResponse> List = projectListData;
        List.forEach(v->{
            for (ProjectBasicResponse projectBasicResponse: allProjectBasicList){
                if (projectBasicResponse.getHrOrganizationId().equals(v.getHrOrganizationId())){
                    v.setHrOrganizationFullName(projectBasicResponse.getHrOrganizationFullName());
                }
            }
        });
        Page<Progress> progressPage = adapterConverter.progressEntityPageToProgress(progressEntityPage);
        if (hrOrganizationId != null &&  List.size()>0) {
            progressPage.getRecords().forEach(v -> {
                for (ProjectBasicResponse projectBasicResponse: List){
                    if (v.getProjectId().equals(projectBasicResponse.getProjectId())) {
                        v.setName(projectBasicResponse.getProjectName());
                        v.setEngineerType(projectBasicResponse.getProjectCategory());
                        v.setGeneralManager(projectBasicResponse.getProjectManager());
                        v.setMainCourtyard(projectBasicResponse.getHrOrganizationFullName());
                        break;
                    }
                }
            });
        }
        //app端 项目视角
        else if (hrOrganizationId == null && CollectionUtils.isEmpty(data)){
            ProjectBasicResponse project = progressProjectRepository.getProject(projectId.longValue());
            if (StringUtils.isNotBlank(projectCategory) && !project.getProjectCategory().equals(projectCategory) || StringUtils.isNotBlank(projectName) && (project.getProjectName().indexOf(projectName) == -1 && project.getProjectManager().indexOf(projectName) == -1) || StringUtils.isNotBlank(projectManager) && project.getProjectManager().indexOf(projectManager) == -1){
                return new Page<>();
            }
            progressPage.getRecords().forEach(v -> {
                v.setName(project.getProjectName());
                v.setEngineerType(project.getProjectCategory());
                v.setGeneralManager(project.getProjectManager());
                v.setMainCourtyard(project.getHrOrganizationFullName());
            });
        }

        progressPage.getRecords().forEach(v -> {
            //默认滞后状态为正常
            v.setMilestoneProgressStatus(1);
            LambdaQueryWrapper<ProgressDetailEntity> progressDetailEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            progressDetailEntityLambdaQueryWrapper.eq(ProgressDetailEntity::getProjectId, v.getProjectId());
            progressDetailEntityLambdaQueryWrapper.like(ProgressDetailEntity::getType, MILESTONE_TYPE);
            List<ProgressDetailEntity> progressDetailEntityList = progressDetailMapper.selectList(progressDetailEntityLambdaQueryWrapper);
            progressDetailEntityList.forEach(item ->{
                if(item.getCompletion() == 0 && item.getStatus() == 0){
                    v.setMilestoneProgressStatus(0);
                }
            });
        });
        return progressPage;
    }

}
